/**
 * Created on : 2016-11-12 00:52:16
 * Author     : @kankan
 */

/************************************************************************************************************************
 ******************************************************** xqupload ******************************************************
 ************************************************************************************************************************/
// create xqupload object
var xqupload = xqupload || {};

(function() {
    
    /**************************************************
     * XQUpload
     **************************************************/
    var XQUpload = function(obj, options) {
		var self = this;
    	
		self.$obj = obj;								// 加了$只是为了区分Js变量而已，可以用来表示这个变量是一个jquery对象，没其他含义
		self.$options = options;
		self.$elem = null;

        // create
		self.$xhr = new XMLHttpRequest();

		self._init();
    };
    
    XQUpload.prototype = {
        /* 初始化 */
        _init: function() {
            var self = this;
            
            self._preProcess();
            self._createDomElem();
            self._show();
    		
            return self;								// VERY IMPORTANT!!! 这样才能继续调用后面的其它方法
        },
        
        /* 预处理 */
        _preProcess: function() {
            var self = this;
            self.$options = $.extend({}, XQUpload.DEFAULTS, self.$options);		// 将调用者的参数与本对象的默认参数进行合并
        },
        
        /* 构建HTML */
        _createDomElem: function() {
            var self = this;
            var progress = $('<div class="progress active" id="' + self.$obj.substring(1) + '-progress" style="display:none;">');			// progress-sm progress-xs progress-xss
            var progressBar = $('<div class="progress-bar progress-bar-warning progress-bar-striped">');
            var progressTxt = $('<span class="progress-txt">test</span>');
            
            progressBar.append(progressTxt);
            progress.append(progressBar);
            
            self.$elem = progress;
        },

        /* _show */
        _show: function() {
            var self = this;
            
            $(self.$obj).after(self.$elem);
            self._execFunc('afterShow');
        },
        
        /* 执行方法 */
        _execFunc: function(type) {
            var self = this;
            
            if (self.$options[type] && typeof self.$options[type] === 'function') {
                self.$options[type](self);
            }
        },

        /******************* 公共方法 *******************/
        /* upload */
        upload: function (formData, key) {
            var self = this;

        	// check filename
            var filename = $(self.$obj).val();
            if (!filename) {
            	return false;
            }

            ////// startDate
            var startDate = new Date().getTime();
            
            ////// formData
//            console.log('uploadUrl = ' + self.$options.uploadUrl);
//            console.log('uploadDomain = ' + self.$options.uploadDomain);
//            console.log('token = ' + self.$options.token);
            var formData = formData ? formData : new FormData();				// 为了兼容lrz
            if (key) {															// key and self.$options.token CANNOT be 0 !!!
            	formData.append('key', key);
            }
            if (self.$options.token) {
            	formData.append('token', self.$options.token);
            }
            formData.append('file', $(self.$obj)[0].files[0]);

            ////// xhr
            // init
            self.abort();
            $(self.$obj + '-progress .progress-bar').css('width', "0%");
            $(self.$obj + '-progress .progress-txt').html("0%");
        	$(self.$obj + '-progress').show();
            console.log('xqupload init complete');
            
            // on ready state change
            self.$xhr.onreadystatechange = function(response) {
                if (self.$xhr.readyState == 4 && self.$xhr.status == 200 && self.$xhr.responseText != "") {
                	$(self.$obj + '-progress').hide();
                	
//        			console.log(self.$xhr.responseText);
                    var blkRet = JSON.parse(self.$xhr.responseText);
                    console && console.log(blkRet);
                	
        			$(self.$options.recvObj).val(self.$options.uploadDomain + blkRet.url);
                } else if (self.$xhr.status != 200 && self.$xhr.responseText) {
                	alert("Problem retrieving XML data");
                }
            };
            
            // progress
            self.$xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var nowDate = new Date().getTime();
                    var taking = nowDate - startDate;
                    var x = (evt.loaded) / 1024;
                    var y = taking / 1000;
                    var uploadSpeed = (x / y);
                    var formatSpeed;
                    
                    if (uploadSpeed > 1024) {
                        formatSpeed = (uploadSpeed / 1024).toFixed(2) + "Mb\/s";
                    } else {
                        formatSpeed = uploadSpeed.toFixed(2) + "Kb\/s";
                    }
                    
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    console && console.log(percentComplete, ",", formatSpeed);
                    
                    $(self.$obj + '-progress .progress-bar').css('width', percentComplete + "%");
                    $(self.$obj + '-progress .progress-txt').html(percentComplete + "%");
                }
            }, false);
            
            // init http params
            self.$xhr.open('POST', self.$options.uploadUrl, true);

            // send http request
            self.$xhr.send(formData);
		},

        /* abort */
        abort: function () {
            var self = this;

            if (self.$xhr.readyState != 0 && self.$xhr.readyState != 4) {
                self.$xhr.abort();
                console.log('xqupload aborted');
            }
        }
    };

    XQUpload.DEFAULTS = {
    	uploadUrl			: '',
    	uploadDomain    	: '',
        token				: '',
        recvObj				: ''
    };
    
    /** xqupload */
	xqupload = function(obj, options) {
		return new XQUpload(obj, options);
    };
    xqupload.defaults = XQUpload.DEFAULTS;
    
})();